package cn.stylefeng.guns.ffmpeg.controller;

import cn.stylefeng.guns.ffmpeg.bean.TranscodeInfo;
import cn.stylefeng.guns.modular.video.model.params.VideoFileParam;
import cn.stylefeng.guns.modular.video.service.VideoFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.HtmlUtils;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

import static cn.stylefeng.guns.ffmpeg.utils.FFmpegUtils.transcodeToM3u8;


/**
 * 测试视屏转码分片
 */
@RestController
@RequestMapping("/video")
@Slf4j
public class FileTestController {
    @Value("${video.file-path}")
    private String videoFolder;

    @Autowired
    private VideoFileService fileService;

    // 获取系统临时目录
//    private Path tempDir = Paths.get(System.getProperty("java.io.tmpdir"));
    private Path tempDir = Paths.get("F:\\videoTemp");
    @GetMapping("/")
    public String index(Model model){
        return "index";
    }

    /**
     * 上传视频进行切片处理，返回访问路径
     *
     * @param video
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    @CrossOrigin
    public Object upload(Long specialtyId, Long stageId, String knowledgeIds,
                         @RequestPart(name = "file", required = true) MultipartFile video) throws IOException {
        TranscodeInfo transcodeConfig = new TranscodeInfo();
        log.info("文件信息：title={}, size={}", video.getOriginalFilename(), video.getSize());
        if(1073741824L < video.getSize() && video.getSize()<= 1610612736L){
            transcodeConfig.setTsSeconds("20");
        }else if(1610612736L < video.getSize() && video.getSize() <= 2147483648L){
            transcodeConfig.setTsSeconds("25");
        }else if(2147483648L < video.getSize() && video.getSize() <= 2684354560L){
            transcodeConfig.setTsSeconds("30");
        }else if(2684354560L < video.getSize() && video.getSize() < 3221225472L){
            transcodeConfig.setTsSeconds("40");
        }else if(video.getSize() > 3221225472L){
            transcodeConfig.setTsSeconds("50");
        }
        log.info("转码配置：{}", transcodeConfig);
        // 原始文件名称，也就是视频的标题
        String title = video.getOriginalFilename();
        // io到临时文件
        Path tempFile = tempDir.resolve(title);
        log.info("io到临时文件：{}", tempFile.toString());
        try {
            video.transferTo(tempFile);
            // 删除后缀
            title = HtmlUtils.htmlUnescape(title.substring(0, title.lastIndexOf(".")).replace(" ",""));
            // 按照日期生成子目录
            //String today = DateTimeFormatter.ofPattern("yyyyMMdd").format(LocalDate.now());
            //按照专业+阶段+知识点生成目录
            // 尝试创建视频目录
            Path targetFolder = Files.createDirectories(Paths.get(videoFolder, specialtyId.toString(), stageId.toString(), knowledgeIds, title));
            log.info("创建文件夹目录：{}", targetFolder);
            Files.createDirectories(targetFolder);
            // 执行转码操作
            log.info("开始转码");
            try {
                transcodeToM3u8(tempFile.toString(), targetFolder.toString(), transcodeConfig);
            } catch (Exception e) {
                log.error("转码异常：{}", e.getMessage());
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", e.getMessage());
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
            }
            String videoAddr = String.join("/", "", specialtyId.toString(), stageId.toString(), knowledgeIds, title, "ts/index.m3u8");
            String posterAddr = String.join("/", "", specialtyId.toString(), stageId.toString(), knowledgeIds, title, "ts/poster.jpg");
            VideoFileParam videoFileParam = new VideoFileParam();
            videoFileParam.setPosterAddr(posterAddr);
            videoFileParam.setStageDataId(stageId);
            videoFileParam.setVideoTitle(title);
            videoFileParam.setVideoAddr(videoAddr);
            Long id = fileService.insertVideoFile(videoFileParam);
            // 封装结果
            Map<String, Object> videoInfo = new HashMap<>();
            videoInfo.put("id", id);
            videoInfo.put("title", title);
            videoInfo.put("m3u8", videoAddr);
            videoInfo.put("poster", posterAddr);

            //返回数据
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("data", videoInfo);
            return result;
        } finally {
            // 始终删除临时文件
            Files.delete(tempFile);
        }
    }

}
